# coding:utf-8
from django.db import models


class BaseModel(models.Model):
    is_delete = models.BooleanField(default=False)
    create_time = models.DateField(auto_now_add=True)
    last_update_time = models.DateField(auto_now=True)

    class Meta:
        abstract = True  # 抽象表，不在数据库建立出表


class Book(BaseModel):
    title = models.CharField(max_length=32)
    price = models.DecimalField(max_digits=5, decimal_places=2)
    # db_constraint=False，逻辑上的关联，实质上没有外键联系，增删不会受外键影响，但是orm查询不影响
    publish = models.ForeignKey(to='Publish', on_delete=models.DO_NOTHING, db_constraint=False)
    # 第三张表只有关联字段，用自动；第三张表有扩展字段，需要手动写；不能写on_delete
    authors = models.ManyToManyField(to='Author', db_constraint=False)

    def __str__(self):
        return self.title

    def publish_name(self):
        return self.publish.name

    def author_list(self):
        author_list = self.authors.all()
        return [{'name': author.name, 'gender': author.get_gender_display()} for author in author_list]


class Publish(BaseModel):
    name = models.CharField(max_length=32)
    addr = models.CharField(max_length=32)

    def __str__(self):
        return self.name


class Author(BaseModel):
    name = models.CharField(max_length=32)
    gender = models.IntegerField(choices=((1, '男'), (2, '女')))
    author_detail = models.OneToOneField(to='AuthorDetail', db_constraint=False, on_delete=models.CASCADE)

    def __str__(self):
        return self.name


class AuthorDetail(BaseModel):
    phone = models.CharField(max_length=32)

    def __str__(self):
        return self.phone
